package com.fqr;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.apache.log4j.Logger;

public class EmailErrorNotifier {
	
	private static final String SENDER = "ErrorNotifier@flex_quartz_runner.com";

	final static Logger logger = Logger.getLogger(EmailErrorNotifier.class);

	public static void notify(String msg) {
		notify(msg, new Throwable());
	}

	public static void notify(String msg, String subject) {
		if (msg == null || msg.toString().trim().length() == 0)
			return;

		try {
			ArrayList<String> to = new ArrayList<String>();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					EmailErrorNotifier.class.getClassLoader()
							.getResourceAsStream("recipients.txt")));
			for (String l = reader.readLine(); l != null; l = reader.readLine()) {
				if (l != null && l.trim().length() > 0) {
					to.add(l);
				}

			}

			EmailInfo email = new EmailInfo();
			email.setEmailfromAdd(SENDER);
			email.setEmailrecAdd(to);
			email.setEmailSubject(subject);
			email.setEmailMessage(msg.toString());

			new EmailUtil().sendEmail(email);
		} catch (Exception e) {
			logger.error("Error sending email", e);
		}
	}

	public static void notify(String msg, Throwable t) {
		if (msg == null)
			msg = "";
		StringBuffer buf = new StringBuffer(msg).append("\n");
		getStrackTrace(t, buf);

		EmailInfo email = new EmailInfo();
		email.setEmailfromAdd(SENDER);
		ArrayList<String> to = new ArrayList<String>();
		to.add(SENDER);
		email.setEmailrecAdd(to);
		email.setEmailSubject("Error");
		email.setEmailMessage(buf.toString());

		new EmailUtil().sendEmail(email);
	}

	private static void getStrackTrace(Throwable t, StringBuffer buf) {
		if (t != null) {
			t.printStackTrace();
			buf.append("caused by").append("\n");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PrintWriter writer = new PrintWriter(bos);
			t.printStackTrace(writer);
			writer.flush();
			buf.append(bos.toString());
			getStrackTrace(t.getCause(), buf);
		}
	}

	public static void main(String[] args) {
		try {
			"yaxin".substring(10, 20);
		} catch (Exception e) {
			EmailErrorNotifier.notify("exception test", e);
		}

		EmailErrorNotifier.notify("error message test");
	}

}
